﻿using Polaris.Common;
using Polaris.Domain.Interfaces.Admin;
using Polaris.Domain.Model.DbEntity;
using Polaris.Domain.Model.Dto.Sys_Dictionary.Request;
using Polaris.Domain.Model.Dto.Sys_Dictionary.Response;
using Polaris.Domain.Model.Entity.Base;
using Polaris.Domain.Model.Entity.Exception;
using Polaris.Domain.Model.Enum;
using Polaris.Domain.Repository.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Polaris.Infrastructure.DomainService.Admin
{
    public class Sys_DictionaryService : ISys_Dictionary
    {
        private readonly IBaseRepository<Sys_Dictionary> _dictionaryRepository;

        public Sys_DictionaryService(IBaseRepository<Sys_Dictionary> dictionaryRepository)
        {
            _dictionaryRepository = dictionaryRepository;
        }


        /// <summary>
        /// 创建字典
        /// </summary>
        /// <param name="create"></param>
        /// <returns></returns>
        /// <exception cref="CustomException"></exception>
        public async Task CreateDictionary(CreateDictionaryRequest create, Guid? userId)
        {
            try
            {
                var dict = new Sys_Dictionary()
                {
                    Id = Guid.NewGuid(),
                    Code = create.Code,
                    CreateBy = userId,
                    CreatedTime = DateTime.Now,
                    Description = create.Description,
                    Enable = true,
                    IsDelete = false,
                    Name = create.Name,
                    Sort = create.Sort,
                    UpdatedBy = null,
                    UpdatedTime = null
                };
                await _dictionaryRepository.AddEntityAsync(dict);
                await _dictionaryRepository.CommitAsync();
            }
            catch (Exception ex)
            {
                throw new CustomException(ResultCode.FAIL, ex.Message);
            }
        }

        /// <summary>
        /// 删除字典
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="CustomException"></exception>
        public async Task DeleteDictionary(string id, Guid? userId)
        {
            var dict = await _dictionaryRepository.WhereLoadEntityAsNoTrackingAsync(d => d.Id.ToString() == id) ??
                        throw new CustomException(ResultCode.NO_DATA, $"字典中找不到Id是 {id} 的数据");

            dict.IsDelete = true;
            dict.UpdatedBy = userId;
            dict.UpdatedTime = DateTime.Now;
            _dictionaryRepository.UpdateEntity(dict);
            await _dictionaryRepository.CommitAsync();

        }

        /// <summary>
        /// 获取字典列表
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PaginationInfo<DictionaryInfoResponse>> GetDictionaryList(SearchDictionaryRequest search)
        {
            Expression<Func<Sys_Dictionary, bool>> where = e => e.IsDelete == false;
            where = where.AndIF(search.Name != null, e => e.Name.Contains(search.Name));
            where = where.AndIF(search.Code != null, e => e.Code.Contains(search.Code));

            var dictList = (await _dictionaryRepository.LoadEntityListAsync(where, e => e.Sort, "asc", search.PageIndex, search.PageSize)
                                                        ).Select(d => new DictionaryInfoResponse
                                                        {
                                                            Code = d.Code,
                                                            CreateBy = d.CreateBy.ToString(),
                                                            CreatedTime = d.CreatedTime,
                                                            Description = d.Description,
                                                            Enable = d.Enable,
                                                            Id = d.Id.ToString(),
                                                            Name = d.Name,
                                                            Sort = d.Sort,
                                                            UpdatedBy = d.UpdatedBy.ToString(),
                                                            UpdatedTime = d.UpdatedTime,
                                                        }).ToList();

            var total = await _dictionaryRepository.GetEntitiesCountAsync(where);
            return ApiResult.CreatePaginationInfo<DictionaryInfoResponse>(
                                                                            PageIndex: search.PageIndex,
                                                                            PageSize: search.PageSize,
                                                                            Total: total,
                                                                            Result: dictList
                                                                           );
        }

        /// <summary>
        /// 根据id获取字典详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<DictionaryInfoResponse> GetDictionaryById(string id)
        {
            var dict = await _dictionaryRepository.WhereLoadEntityAsync(d => d.Id.ToString() == id);
            var result = new DictionaryInfoResponse
            {
                Id = dict.Id.ToString(),
                Code = dict.Code,
                Description = dict.Description,
                Enable = dict.Enable,
                Name = dict.Name,
                Sort = dict.Sort,
            };

            return result;
        }
        /// <summary>
        /// 修改字典
        /// </summary>
        /// <param name="update"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="CustomException"></exception>
        public async Task UpdateDictionary(UpdateDictionaryRequest update, Guid? userId)
        {
            try
            {
                var dict = await _dictionaryRepository.WhereLoadEntityAsNoTrackingAsync(d => d.Id.ToString() == update.Id) ??
                            throw new CustomException(ResultCode.NO_DATA, $"字典中找不到Id是 {update.Id} 的数据");
                dict.Sort = update.Sort;
                dict.Name = update.Name;
                dict.Description = update.Description;
                dict.UpdatedBy = userId;
                dict.UpdatedTime = DateTime.Now;
                dict.Code = update.Code;
                dict.Enable = update.Enable;
                _dictionaryRepository.UpdateEntity(dict);
                await _dictionaryRepository.CommitAsync();
            }
            catch (Exception ex)
            {
                throw new CustomException(ResultCode.FAIL, ex.Message);
            }
        }


    }
}
